<?php

namespace App\Exceptions;

use stdClass;

/**
 * 返回值定义
 * Class R
 * @package app\common
 */
abstract class R
{
    const SUCCESS           = 0;//一般成功
    const ERROR             = 1;//未定义错误
    const HEADER_ERROR      = 40001;//header信息错误
    const ROUTER_NOT_EXIST  = 40004;//接口不存在
    const ROUTER_PARAM_MISS = 40005;//接口缺少参数
    const INVALID_REQUEST   = 40006;//非法请求
    const INPUT_DATA_ERROR  = 70000;//输入数据未通过验证
    const INNER_ERROR       = 99999;//服务器内部错误

    /**
     * 跨域头
     * @var array
     */
    public static $header = [
        'Access-Control-Allow-Origin'      => '*',
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE',
        'Access-Control-Allow-Headers'     => 'type, Access-Token, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With,authorization',
        'Access-Control-Expose-Headers'    => 'Authorization',
        'X-Powered-By'                     => 'Mula.com'
    ];

    /**
     * 有结构数据返回
     * @param array  $data
     * @param int    $code
     * @param string $msg
     * @param int    $http_code
     * @return \Illuminate\Http\JsonResponse|object
     */
    public static function Api(array $data = [], int $code = self::SUCCESS, string $msg = '', int $http_code = 200)
    {
        $header = self::$header + [
                'X-Powered-By'  => 'Mula.com',
                'authorization' => request()->token ? request()->token : ''
            ];
        return response()->json([
                                    'code' => $code,
                                    'msg'  => $msg,
                                    'time' => time(),
                                    'data' => $data ?: new stdClass(),
                                ], $http_code, $header);
    }

    /**
     * 无数据的状态返回
     * @param int    $code
     * @param string $msg
     * @param int    $http_code
     */
    public static function ApiSimple($code = self::SUCCESS, $msg = '', $http_code = 200)
    {
        $header = self::$header + [
                'X-Powered-By'  => 'Mula.com',
                'authorization' => request()->token ? request()->token : ''
            ];
        response()->json([
                             'code' => $code,
                             'msg'  => $msg,
                             'time' => time(),
                             'data' => new stdClass(),
                         ], $http_code, $header);
    }
}
